package idv.loveloser.servlet;

import idv.loveloser.dao.MdlAssignment;
import idv.loveloser.dao.MdlAssignmentDAO;
import idv.loveloser.dao.MdlContext;
import idv.loveloser.dao.MdlContextDAO;
import idv.loveloser.dao.MdlCourseDAO;
import idv.loveloser.dao.MdlGradeGrades;
import idv.loveloser.dao.MdlGradeGradesDAO;
import idv.loveloser.dao.MdlGradeItems;
import idv.loveloser.dao.MdlGradeItemsDAO;
import idv.loveloser.dao.MdlRoleAssignments;
import idv.loveloser.dao.MdlRoleAssignmentsDAO;
import idv.loveloser.dao.MdlUserDAO;
import idv.loveloser.util.Util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonObject;

public class GetAssignmentGrade extends HttpServlet {
	private MdlUserDAO userDAO = new MdlUserDAO();
	private MdlContextDAO contextDAO=new MdlContextDAO();
	private MdlCourseDAO courseDAO = new MdlCourseDAO();
	private MdlRoleAssignmentsDAO roleAssignmentDAO = new MdlRoleAssignmentsDAO();
	private MdlAssignmentDAO assignmentDAO =new MdlAssignmentDAO();
	private MdlGradeItemsDAO gradeItemDAO = new MdlGradeItemsDAO();
	private MdlGradeGradesDAO gradeGradesDAO = new MdlGradeGradesDAO();
	private static final long CPNTEXT_COURSE=50L;
	/**
	 * Constructor of the object.
	 */
	public GetAssignmentGrade() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		String client = request.getParameter("client");
		String sessionKey = request.getParameter("sessionKey");
		String courseId=request.getParameter("courseId");
		String assignmentId = request.getParameter("assignmentId");
		boolean available=true;
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		long userId =Util.getUserId(Long.parseLong(client));
		boolean returnBool=false;
		JsonObject json = new JsonObject();
		long contextId=-1L;
		double finalGrade=0.0;
		if(Util.isAuthorised(client, sessionKey)){
			List<MdlContext> contexts=contextDAO.findByContextlevel(CPNTEXT_COURSE);
			for(int index=0;index<contexts.size();index++){
				MdlContext context =contexts.get(index);
				if(context.getInstanceid()==Long.parseLong(assignmentId)						){
					contextId =context.getId();
					break;
				}
			}
			List<MdlRoleAssignments> roles = roleAssignmentDAO.findByContextid(contextId);
			for(int index=0;index<roles.size();index++){
				MdlRoleAssignments role = roles.get(index);
				if((role.getRoleid()==5L) && (role.getUserid()==userId) || (role.getRoleid()<3)){
					returnBool=true;
					break;
				}
			}
			if(returnBool){
				MdlAssignment assignment = assignmentDAO.findById(Long.parseLong(assignmentId));
				if((assignment.getTimedue()*1000)<System.currentTimeMillis()){
					available=false;
				}
				List<MdlGradeItems> gradeItems=gradeItemDAO.findByCourseid(Long.parseLong(courseId));
				MdlGradeItems selectedItem=null;
				for(int index=0;index<gradeItems.size();index++){
					if((gradeItems.get(index).getIteminstance()==Long.parseLong(assignmentId)) &&
							(gradeItems.get(index).getItemmodule().equals("assignment")) &&
							(gradeItems.get(index).getItemtype().equals("mod"))
							){
						selectedItem=gradeItems.get(index);
						break;
					}
				}
				List<MdlGradeGrades> grades=gradeGradesDAO.findByItemid(selectedItem.getId());
				if(grades.size()>0)
					try{
						finalGrade=grades.get(0).getFinalgrade();
					}catch(NullPointerException npe){
						finalGrade=0D;
					}
				else
					finalGrade=-1D;
			}
			
			json.addProperty("hasPermission", returnBool);
			json.addProperty("finalGrade", finalGrade);
			out.println(json);
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
